package tongwentongshu.com.app.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.tencent.imsdk.TIMCallBack;
import com.tencent.imsdk.TIMFriendAllowType;
import com.tencent.imsdk.TIMFriendshipManager;
import com.tencent.imsdk.TIMManager;
import com.umeng.message.PushAgent;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import tencent.tls.platform.TLSLoginHelper;
import tongwentongshu.com.app.App;
import tongwentongshu.com.app.MapMainActivity;
import tongwentongshu.com.app.R;
import tongwentongshu.com.app.activityim.UserInfo;
import tongwentongshu.com.app.bean.AppItem;
import tongwentongshu.com.app.bean.InfoEvent;
import tongwentongshu.com.app.bean.LoginEvent;
import tongwentongshu.com.app.bean.MessageEvent;
import tongwentongshu.com.app.bean.MoneyEvent;
import tongwentongshu.com.app.bean.UrlEvent;
import tongwentongshu.com.app.contract.CallBackColonyContract;
import tongwentongshu.com.app.db.Cache;
import tongwentongshu.com.app.dialog.AlertUtils;
import tongwentongshu.com.app.network.ResponseSubscriber;
import tongwentongshu.com.app.update.UpdateFractory;
import tongwentongshu.com.app.utils.SpUtils;

/**
 * Created by shiqiang on 2017/3/23.
 */

public abstract class BaseActivity extends CheckPermissionsActivity {

    protected final String TAG = this.getClass().getName();
    protected Context mContext;
    private Unbinder bind;
    protected int layoutResourceId;
    protected boolean onRefreshJudge = false;
    protected boolean onLoadMoreJudge = false;
    protected boolean _Judge = true;//是否开启监听未登录
    @BindView(R.id.tv_title_name)
    TextView title;//title
    @BindView(R.id.title_back)
    ImageView back;//返回键
    private Map<String, String> map;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        layoutResourceId = getLayoutResourceId();
        setContentView(layoutResourceId);
        bind = ButterKnife.bind(this);
        PushAgent.getInstance(mContext).onAppStart();
        if (this.getClass() != MapMainActivity.class)
            App.getApplication().addMallActivity(this);
        Bundle extras = getIntent().getExtras();
        if (null != extras) {
            getBundleExtras(extras);
        }
        title.setText(getTitleId());
        initView();
        initBundle(savedInstanceState);
        initListener();
        initData();
        setEventBus();
    }

    protected void setEventBus() {
        EventBus.getDefault().register(this);
    }

    public void onEventMainThread(UrlEvent result) {
        if (_Judge) {
            Intent i = new Intent(mContext, WebViewActivity.class);
            i.putExtra("url", result.getResult());
            startActivity(i);
//            mContext.startActivity(i);
        }
    }

    public void onEventMainThread(InfoEvent result) {
        if (_Judge) {
            AlertUtils.showInfoShare(mContext, "知道了", result.getResult(), new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                }
            });

        }
    }

    public void onEventMainThread(MoneyEvent result) {
        if (_Judge) {
            AlertUtils.showAgainShare(mContext, "书豆不足，是否去充值？", "取消", "去充值", 2, new CallBackColonyContract.OnDiyClick() {
                @Override
                public void left() {

                }

                @Override
                public void right() {
                    Bundle b = new Bundle();
                    b.putString("shudou", Cache.getUser().getData().getDoudou() + "书豆");
                    startActivity(RechargeActivity.class, b);
                }
            });

        }
    }

    public void onEventMainThread(MessageEvent result) {
        if (_Judge) {
            if (result.getMessage_style().equals("1")) {
                Bundle b = new Bundle();
                b.putBoolean("pager_Judge", false);
                b.putString("pagerType", "1");
                b.putString("bookId", result.getBook_id());
                startActivity(ReadingDetailsActivity.class, b);
            } else if (result.getMessage_style().equals("2")) {
                startActivity(ShudouActivity.class);
            } else if (result.getMessage_style().equals("3")) {
                startActivity(DepositDetailsActivity.class);
            } else if (result.getMessage_style().equals("4")) {
                Bundle b = new Bundle();
                if (result.getIs_auth().equals("1")) {
                    b.putBoolean("pager_Judge", true);
                } else {
                    b.putBoolean("pager_Judge", false);
                }
                b.putString("pagerType", "1");
                b.putString("bookId", result.getBook_id());
                startActivity(ReadingDetailsActivity.class, b);

            } else {
                Bundle b = new Bundle();
                b.putString("url", result.getMessurl());
                startActivity(WebViewActivity.class, b);

            }
            chengeMessage(result.getMessid());

        }
    }

    public void chengeMessage(String message_id) {
        map = new ArrayMap<>();
        map.put("messid", message_id);

        UpdateFractory.getBuild()
                .name("UpdateMessageCall")
                .map(map)
                .build()
                .execute(new ResponseSubscriber<AppItem>() {

                    @Override
                    public void onFailure(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onSuccess(AppItem bean, String msg) {
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }
                });
    }

    public void onEventMainThread(LoginEvent result) {
        if (_Judge) {
            Log.e(TAG, Cache.getToken());
            AlertUtils.showInfoShare(mContext, "重新登录", "您的账号已在其他手机登录", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(LoginActivity.class);
                    App.getApplication().exitMall();
                }
            });

        }
    }

    CallBackColonyContract.OnCheck check;

    //检验im是否登录
    public void checkIM(CallBackColonyContract.OnCheck check) {
        this.check = check;
        if (TextUtils.isEmpty(TIMManager.getInstance().getLoginUser())) {
            initMSG();
        } else {
            check.check();
        }
    }

    public void initMSG() {
        TLSLoginHelper loginHelper = TLSLoginHelper.getInstance().init(getApplicationContext(),
                1400036219, 14371, SpUtils.getString(mContext, Cache.USER_NAME, ""));
//        loginHelper.setTimeOut(TLSConfiguration.TIMEOUT);
//        loginHelper.setLocalId(TLSConfiguration.LANGUAGE_CODE);
        loginHelper.setTestHost("", true);                   // 走sso
        final String identify = SpUtils.getString(mContext, Cache.USER_NAME, "");
        final String userSig = Cache.getUser().getData().getSig();
        TIMManager.getInstance().login(identify, userSig, new TIMCallBack() {
            @Override
            public void onError(int code, String desc) {
                //错误码code和错误描述desc，可用于定位请求失败原因
                //错误码code列表请参见错误码表
                Log.d("shiqiang", "login failed. code: " + code + " errmsg: " + desc);
                System.out.println("wocBUGkle");
            }

            @Override
            public void onSuccess() {
                Log.d("shiqiang", "login succ");
                System.out.println("wochenggongkle");


                UserInfo.getInstance().setId(identify);
                UserInfo.getInstance().setUserSig(userSig);

                setAddType();
                if (check != null)
                    check.check();

            }
        });
    }

    public void setAddType() {
        //设置自己的好友验证方式为需要验证
        TIMFriendshipManager.ModifyUserProfileParam param = new TIMFriendshipManager.ModifyUserProfileParam();
        param.setAllowType(TIMFriendAllowType.TIM_FRIEND_ALLOW_ANY);

        TIMFriendshipManager.getInstance().modifyProfile(param, new TIMCallBack() {
            @Override
            public void onError(int code, String desc) {
                //错误码code和错误描述desc，可用于定位请求失败原因
                //错误码code列表请参见错误码表
                Log.e(TAG, "modifyProfile failed: " + code + " desc" + desc);
            }

            @Override
            public void onSuccess() {
                Log.e(TAG, "modifyProfile succ");

//                setResult(100);
//                finish();//此处一定要调用finish()方法

            }
        });

    }

    /**
     * 获取资源布局id
     *
     * @return 资源布局id
     */
    protected abstract int getLayoutResourceId();

    /**
     * 获取title id
     *
     * @return 资源布局id
     */
    protected abstract int getTitleId();


    /**
     * Bundle  传递数据
     *
     * @param extras
     */
    protected void getBundleExtras(Bundle extras) {
    }

    /**
     * Bundle保存activity实例
     */
    protected void initBundle(Bundle bundle) {
        System.out.println("我是base里面的Bundle");

    }

    ;

    /**
     * 初始化view
     */
    protected abstract void initView();

    /**
     * 监听事件处理
     */
    protected void initListener() {
        if (null != back)
            back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
    }

    ;

    /**
     * 初始化数据
     */
    protected abstract void initData();


    @Override
    protected void onResume() {
        _Judge = true;
        super.onResume();
    }


    @Override
    protected void onPause() {
        _Judge = false;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        check = null;
    }

    /**
     * [页面跳转]
     *
     * @param clz
     */
    public void startActivity(Class<?> clz) {
        startActivity(new Intent(BaseActivity.this, clz));
    }

    /**
     * 携带数据页面跳转
     *
     * @param clz
     * @param bundle
     */
    public void startActivity(Class<?> clz, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(this, clz);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 含有Bundle通过Class打开编辑界面
     *
     * @param cls
     * @param bundle
     * @param requestCode
     */
    public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(this, cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
    }

    /**
     * 含有Bundle通过Class打开编辑界面
     *
     * @param bundle
     * @param resultCode
     */
    public void resultFinish(Bundle bundle, int resultCode) {
        Intent intent = this.getIntent();
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        this.setResult(resultCode, intent);//返回页面1
        this.finish();
    }


}
